<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>系统设置</el-breadcrumb-item>
      <el-breadcrumb-item>数据源管理</el-breadcrumb-item>
      <el-breadcrumb-item>数据库连接</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="table-wrap-box">
      <div class="header-box">
        <div class="search-param-box">
          <el-form ref="menuForm"
                   :model="searchParams"
                   label-width="100px" size="small">
            <el-row :gutter="50">
              <el-col :span="25">
                <el-form-item label="连接名称：">
                  <el-input v-model="searchParams.name" placeholder="请输入连接名称"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="25">
                <el-form-item label="驱动类型：">
                  <el-select
                      v-model="searchParams.driveType"
                      placeholder="请选择驱动类型"
                      size="small"
                      @change="">
                    <el-option
                        v-for="item in driveTypes"
                        :key="item"
                        :label="item"
                        :value="item">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="25">
                <el-form-item label="主机：">
                  <el-input v-model="searchParams.host" placeholder="请输入主机地址"></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="25">
                <el-button icon="el-icon-search" size="small" type="primary" @click="">搜索</el-button>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div class="top-btns-box">
          <el-button size="mini" style="margin-left: 20px" @click="newConnection">新建连接</el-button>
          <el-button size="mini" style="margin-left: 20px" type="danger" @click="batchDelete">批量删除</el-button>
        </div>
      </div>

      <div class="ds-table">
        <el-table
            :data="connectionList"
            border
            row-key="id"
            size="mini"
            style="width: 100%"
            @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="40">
          </el-table-column>
          <el-table-column v-for="item in columns" :label="item.label" :prop="item.prop" :width="item.width"
                           align="center">
            <template slot-scope="scope">
              <span v-if="item.oper">
                <el-button size="mini" type="text" @click="editClick(scope.row)">编辑</el-button>
                <el-button size="mini" type="text">删除</el-button>
              </span>
              <span v-else>{{ scope.row[item.prop] }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <BaseDialog ref="baseDlg" @ok-click="saveConnection">
      <template #content>
        <ConnectionForm ref="connForm"/>
      </template>
      <template #tool-btn>
        <el-button size="small" @click="testConnect">测试连接</el-button>
      </template>
    </BaseDialog>

  </div>
</template>

<script>
import BaseDialog from "@/components/dialog/BaseDialog";
import ConnectionForm from "@/components/datasource/ConnectionForm";
import {CommUtil} from "@/utils/CommonUtil";
import {AES_Encrypt, AES_Decrypt} from "@/utils/AesUtil";

import {$DataSourceApi} from "@/network/datasource/DataSourceApi";
import {$SysMenuApi} from "@/network/menu/SysMenuApi";

export default {
  name: "DataSourceList",
  components: {
    ConnectionForm,
    BaseDialog
  },
  data() {
    return {
      searchParams: {
        name: '',
        driveType: '',
        host: '',
      },
      columns: [
        {prop: 'name', label: '名称', width: "100", oper: false},
        {prop: 'driveType', label: '驱动类型', width: "100", oper: false},
        {prop: 'host', label: '主机', width: "120", oper: false},
        {prop: 'port', label: '端口', width: "80", oper: false},
        {prop: 'url', label: '连接URL', width: "260", oper: false},
        {prop: 'createTime', label: '创建时间', width: "180", oper: false},
        {prop: 'createBy', label: '创建人', width: "100", oper: false},
        {label: "操作", width: "200", oper: true}
      ],
      connectionList: [],
      showDlg: false,
      driveTypes: ['MySQL', 'Qracle', 'SQLServer'],
      operType: 'add',
      editConnData: {},
      checkedIds: [],
    }
  },
  methods: {

    // 加载数据
    async loadConnectionData() {
      let res = await $DataSourceApi.list();
      this.connectionList = res.data;
    },

    search() {

    },

    // 新建连接
    newConnection() {
      this.$refs.baseDlg.showDialog("新建连接");
      this.operType = 'add';
    },

    // 批量删除
    batchDelete() {

      let ids = CommUtil.toPlainObject(this.checkedIds);
      if (!ids || ids.length === 0) {
        this.$message.error("请选择要删除的菜单");
        return;
      }
      this.$confirm('将删除选择的连接, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await $DataSourceApi.batchDelete({ids});
        if (this.$ResHandle.isOk(res)) {
          this.$message.success(res.msg);
          await this.loadConnectionData();
        } else {
          this.$message.error(res.msg);
        }
      }).catch(err => {
        this.$message.success("取消操作");
      })
    },

    // 测试连接
    async testConnect() {
      let data = CommUtil.toPlainObject(this.$refs.connForm.takeFormData());
      let pwd = data.password;
      data.password = AES_Encrypt(pwd);   // 密码加密
      let res = await $DataSourceApi.testConnect(data);
      if (this.$ResHandle.isOk(res)) {
        this.$message.success("连接成功!");
      } else {
        this.$message.error(res.msg);
      }
    },


    handleSelectionChange(val) {
      this.checkedIds = val.map(item => {
        return item.id;
      })
    },

    handleDlgClose() {
      this.showDlg = false;
      this.$refs.connForm.$destroy();
    },

    async saveConnection() {
      let data = CommUtil.toPlainObject(this.$refs.connForm.takeFormData());
      let pwd = data.password;
      data.password = AES_Encrypt(pwd);
      let res = null;
      if (this.operType === 'add') {
        res = await $DataSourceApi.createConnection(data);
      } else {
        res = await $DataSourceApi.updateConnection(data);
      }
      if (this.$ResHandle.isOk(res)) {
        this.$message.success(res.msg);
      } else {
        this.$message.error(res.msg);
      }
      this.$refs.baseDlg.closeDialog();
      await this.loadConnectionData();
    },

    // 行编辑
    editClick(row) {
      this.operType = 'edit';
      row.password = AES_Decrypt(row.password);
      setTimeout(() => {
        // 这里使用延时防止 $bus.on 先于 $bus.emit 执行
        this.$bus.emit('edit-conn', 'edit', row);
      }, 100)
      this.$refs.baseDlg.showDialog("编辑连接");
    }

  },

  created() {
    this.loadConnectionData();
  }

}
</script>

<style scoped>
.table-wrap-box {
  margin-top: 20px;
  height: 100%;
}

.header-box {
  width: 100%;
  justify-content: space-between;
}

.ds-table {
  margin-top: 10px;
}

.top-btns-box {
  display: flex;
}

</style>
